"""
数据库初始化脚本
创建时间：2025-09-21
作者：开发团队
目的：初始化数据库并添加测试数据
"""

import sys
import os

# 添加项目路径
sys.path.append(os.path.join(os.path.dirname(__file__), 'backend', 'src'))

# 设置环境变量
os.environ['ENVIRONMENT'] = 'development'

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from backend.src.core.database import Base
from backend.src.models.user import User
from backend.src.models.campus import Campus
from backend.src.core.security import get_password_hash
from backend.src.core.config import get_config

def init_database():
    """初始化数据库"""
    print("开始初始化数据库...")
    
    try:
        # 获取配置
        config = get_config()
        print(f"数据库URL: {config.DATABASE_URL}")
        
        # 创建数据库引擎
        engine = create_engine(config.DATABASE_URL, echo=False)
        
        # 创建所有表
        print("正在创建数据库表...")
        Base.metadata.create_all(bind=engine)
        print("数据库表创建完成")
        
        # 创建会话
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        db = SessionLocal()
        
        # 检查是否已存在默认数据
        admin_user = db.query(User).filter(User.username == "admin").first()
        if not admin_user:
            # 创建默认管理员账户
            admin_user = User(
                username="admin",
                password_hash=get_password_hash("admin123"),
                name="系统管理员",
                role="superadmin",
                status="active"
            )
            db.add(admin_user)
            print("默认管理员账户创建成功: username=admin, password=admin123")
        else:
            print("默认管理员账户已存在")
        
        # 检查是否已存在院区数据
        campus = db.query(Campus).first()
        if not campus:
            # 创建默认院区
            campus = Campus(
                name="主院区",
                address="北京市朝阳区",
                contact_person="管理员",
                contact_phone="010-12345678"
            )
            db.add(campus)
            db.commit()
            print("默认院区创建成功: name=主院区")
        else:
            print("默认院区已存在")
        
        # 检查是否已存在门卫账户
        guard_user = db.query(User).filter(User.role == "guard").first()
        if not guard_user:
            # 创建默认门卫账户
            guard_user = User(
                username="guard001",
                password_hash=get_password_hash("123456"),
                name="门卫001",
                role="guard",
                campus_id=campus.id,
                status="active"
            )
            db.add(guard_user)
            
            # 创建更多门卫账户
            for i in range(2, 6):
                guard = User(
                    username=f"guard00{i}",
                    password_hash=get_password_hash("123456"),
                    name=f"门卫00{i}",
                    role="guard",
                    campus_id=campus.id,
                    status="active"
                )
                db.add(guard)
            
            db.commit()
            print("默认门卫账户创建成功: username=guard001, password=123456")
        else:
            print("门卫账户已存在")
        
        # 查询并显示所有门卫账户
        guards = db.query(User).filter(User.role == "guard").all()
        print(f"\n当前门卫账户列表:")
        for guard in guards:
            print(f"  ID: {guard.id}, 用户名: {guard.username}, 姓名: {guard.name}, 状态: {guard.status}")
        
        db.close()
        print("\n数据库初始化完成")
        
    except Exception as e:
        print(f"数据库初始化过程中出现错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    init_database()